package com.mx.tool.form.window.zh;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mx.tool.util.NotifyUtil;
import org.apache.commons.lang3.StringUtils;

import javax.swing.*;
import java.util.List;

/**
 * @Author: 徐建鹏.
 * @create: 2021-11-10 11:26
 * @Description:
 */
public class JsonToolWindow {

    private JPanel jPanel;

    private JTextArea jsonArea;
    private JButton ysButton;
    private JButton formatButton;

    public JsonToolWindow() {
        formatButton.addActionListener(e -> {
            String content = jsonArea.getText();
            if(StringUtils.isNotBlank(content)){
                try {
                    Object obj = JSON.parse(content);
                    if(obj instanceof List){
                        JSONArray jsonArray = (JSONArray) obj;
                        jsonArea.setText(JSON.toJSONString(jsonArray,true));
                    }else{
                        JSONObject jsonObject = (JSONObject) obj;
                        jsonArea.setText(JSON.toJSONString(jsonObject,true));
                    }

                }catch (Exception ex){
                    NotifyUtil.error(ex.getMessage());
                    ex.printStackTrace();
                }
            }
        });
        ysButton.addActionListener(e -> {
            String content = jsonArea.getText();
            if(StringUtils.isNotBlank(content)){
                try {
                    Object obj = JSON.parse(content);
                    if(obj instanceof List){
                        JSONArray jsonArray = (JSONArray) obj;
                        jsonArea.setText(JSON.toJSONString(jsonArray));
                    }else{
                        JSONObject jsonObject = (JSONObject) obj;
                        jsonArea.setText(JSON.toJSONString(jsonObject));
                    }
                }catch (Exception ex){
                    NotifyUtil.error(ex.getMessage());
                    ex.printStackTrace();
                }
            }
        });
    }

    public JPanel getContent() {
        return jPanel;
    }
}
